

import Command from '@ckeditor/ckeditor5-core/src/command';
import first from '@ckeditor/ckeditor5-utils/src/first';

const INDENT = 'indent';

export default class Indentcommand extends Command {

	/**
	 * Updates the command's {@link #value} and {@link #isEnabled} based on the current selection.
	 */
	refresh() {
		const firstBlock = first( this.editor.model.document.selection.getSelectedBlocks() );

		this.isEnabled = true;
	}

	execute() {
		const editor = this.editor;
		const model = editor.model;
		const doc = model.document;

		model.change( writer => {
			// Get only those blocks from selected that can have alignment set
			const blocks = Array.from( doc.selection.getSelectedBlocks() );
			const currentAlignment = blocks[ 0 ].getAttribute( INDENT );
			if(currentAlignment==null){
				setIndentOnSelection( blocks, writer, 20 );
			}else{
				setIndentOnSelection( blocks, writer, parseFloat(currentAlignment)+20 );
			}
		} );

	}


	/**
	 * Checks whether a block can have alignment set.
	 *
	 * @private
	 * @param {module:engine/model/element~Element} block The block to be checked.
	 * @returns {Boolean}
	 */
	_canBeAligned( block ) {
		return this.editor.model.schema.checkAttribute( block, INDENT );
	}
}

// Sets the alignment attribute on blocks.
// @private
function setIndentOnSelection( blocks, writer, indentValue ) {
	for ( const block of blocks ) {
		writer.setAttribute( INDENT, indentValue, block );
	}
}
